import random

from util.common import *


def process_cloud():
    target = [
        ('ASSE0468843960225856', '10.47.201.70'),
        ('ASSE2221802703692740', '10.48.131.112'),
        ('ASSE5346070735646638', '10.47.231.196'),
    ]

    df = read_excel("source/opernstack.xlsx")
    itemIds = df['ITEM_ID'].to_list()
    list = []

    for createTime in generate_workdays('2024-09-01', '2024-11-28', 1):
        id = "CLODZX" + random_string(14)

        timeSpan = random.randrange(2, 20)
        start_date, end_date = get_random_date(createTime, timeSpan)

        # random_record = filtered_df.sample(n=1)
        # assetId = random_record['ID'].item()
        # iIP = random_record["INTRANET_IP"].item()
        # iIP = None if pd.isna(iIP) else iIP
        (assetId, iIP) = random.choice(target)
        seep = {
            "taskId": id,
            "taskName": f"检查任务-{iIP}-{createTime[:10]}",
            "taskSource": "3",
            "taskFlag": "9",
            "mainTaskId": None,
            "taskCreator": "PORT6452766823027939",
            "taskResponser": "PORT6452766823027939",
            "taskDesp": None,
            "taskStatus": "3",
            "woId": "1",
            "bussIds": assetId,
            "decomposedType": None,
            "decomposedStatus": "",
            "decomposedFlag": "",
            "executeStatus": "",
            "checkTypes": "3_1",
            "itemRange": "2",
            "sysHoleDeviceId": None,
            "sysTempId": None,
            "sysTempName": None,
            "sysTempuuid": None,
            "webHoleDeviceId": None,
            "webTempId": None,
            "webTempName": None,
            "source": None,
            "idLvl": None,
            "idFlag": id,
            "executeNum": "0",
            "scannerDesc": None,
            "taskType": "0",
            "scannerParam": '{"advanceFlag":"1","advancedPath":"","charSet":"UTF-8","checkAddtional":"no","defaultScanner":"","deviceOsId":"BVS113007000","enableUnsafePlugins":"no","ifDebug":"no","isGuesspwd":"no","live":"no","liveArp":"no","liveIcmp":"no","liveTcp":"no","liveTcpPorts":"21,22,23,25,80,443,445,139,3389,6000","liveUdp":"no","liveUdpPorts":"25,53","messTypes":"5;6;7;8;9;10;11;12;13;14;15;16;17;18;20;21;22;23;24;25;26;27;28","openSsh":"no","osMatch":"no","pluginTemplateId":"","pluginTemplateName":"","policyId":"","portSpeed":"3","portStrategy":"standard","portStrategyUserports":"1-100,443,445","portTcp":"T","portUdp":"no","pwdInterval":"0","pwdNum":"0","pwdPluginset":"2002;2012;2004;2005","pwdThreadnum":"5","pwdTimeout":"30","pwdUserid":"2","pwdUsername":"admin","pwdVulset":"2002;2012;2004;2005","reportContent":"sum,host","reportIfcreate":"no","reportIfsent":"no","reportIfsentEmail":"","reportIfsentType":"html","reportTplhost":"101","reportTplsum":"1","reportType":"html,doc,xls,pdf,xml","scanAlert":"no","scanHuawei":"no","scanLevel":"3","scannerFlag":"0","scannerId":"ASSE0123369033078976","scannerName":"亚信安全基线工具-1","sendFtp":"no","spingDelay":"1","timeoutPlugins":"60","timeoutRead":"30"}',
            "beginTime": start_date,
            "endTime": end_date,
            "createTime": start_date,
            "updateTime": end_date,
            "actualStartTime": start_date,
            "actualEndTime": end_date,
            "platForm": '0',
            "cycStr": None,
            "taskClass": "1",
        }
        message1 = render_template("""
               insert into TF_SA_COMPLIANCE_TASK(TASK_ID, TASK_NAME, TASK_SOURCE, TASK_FLAG, MAIN_TASK_ID, TASK_CREATOR,
                                          TASK_RESPONSER, BEGIN_TIME, END_TIME, CREATE_TIME, TASK_DESP,
                                          TASK_STATUS, UPDATE_TIME, WO_ID, TASK_BUSSIDS, DECOMPOSED_TYPE,
                                          DECOMPOSED_STATUS, DECOMPOSED_FLAG, EXECUT_STATUS, ITEM_TYPE, ITEM_RANGE,
                                          SYS_SCANNER_ID, SYS_TEMP, SYS_TEMP_NAME, SYS_UUID, WEB_SCANNER_ID, WEB_TEMP,
                                          WEB_TEMP_NAME, SOURCE, ID_LVL, ID_FLAG, EXECUTE_NUM,
                                          SCANNERDESC, TASK_TYPE, SCANNER_PARAM, ACTUAL_START_TIME, PLAT_FORM, CYC_STR, TASK_CLASS, ACTUAL_END_TIME)
               values ($taskId, $taskName, $taskSource, $taskFlag, $mainTaskId, $taskCreator, $taskResponser,
                            $beginTime, $endTime, $createTime, $taskDesp,
                            $taskStatus, $updateTime, $woId, $bussIds, $decomposedType, $decomposedStatus, $decomposedFlag,
                            $executeStatus, $checkTypes, $itemRange,
                            $sysHoleDeviceId, $sysTempId, $sysTempName, $sysTempuuid, $webHoleDeviceId, $webTempId,
                            $webTempName, $source, $idLvl, $idFlag, $executeNum,
                            $scannerDesc, $taskType, $scannerParam, $actualStartTime, $platForm, $cycStr, $taskClass, $actualEndTime);
            """, seep)

        list.append(message1)

        report = {
            "id": id,
            "taskId": id,
            "itemId": assetId,
            "startTime": start_date,
            "ip": iIP,
        }

        message2 = render_template(
            """
                    INSERT INTO TF_SA_QUICK_TASK_TO_ITEM(ID, TASK_ID, ITEM_ID, ASSET_CHECK_STATUS, SUITABLE_NUM, CHECKED_NUM, UNCHECKED_NUM,
                                     COMPLIANCE_NUM, UNCOMPLIANCE_NUM, ABNORMAL_NUM, ASSET_CHECK_FAILREASON,
                                     UNSUITABLE_NUM, SHADOW_NAME, CREATE_TIME, TASK_TYPE, ASSET_IP, ASSET_HW_TYPE,
                                     MINING_RISK, ORIGINAL_ASSET_NAME, ORIGINAL_HW_TYPE)
                    VALUES ($id, $taskId, $itemId, '1', '40', '40', '0', '32', '8', '0',
                            NULL, '0', NULL, $startTime, '3', $ip, 'DR-LIN', NULL,
                            NULL, NULL);
                """,
            report)
        list.append(message2)

        sql_file = '/xlsx/TF_SA_TASK_ITEM_RESULT.sql'
        item_temp_pair = zip(itemIds, read_sql_file(sql_file))

        for itemId, line in item_temp_pair:
            item = line.strip().replace("\n", "").strip()
            if not item:
                continue
            seep = {
                "id": "CLODZX" + random_string(14),
                "taskId": id,
                "assetId": assetId,
                "saveTime": start_date,
                "iIP": iIP,
                "itemId": itemId,
            }
            list.append(render_template(item, seep))


if __name__ == '__main__':
    process_cloud()
    # sestssy()

#     seep = {
#         "id": "CLODZX" + random_string(14),
#         "taskId": "",
#         "assetId": "",
#         "saveTime": "",
#         "iIP": "",
#     }
#     render_template("""
# INSERT INTO TF_SA_TASK_ITEM_RESULT("RESULT_ID", "TASK_ID", "ITEM_ID", "ASSET_ID", "CHECK_RESULT", "RESULT_DESP", "SAVE_TIME", "COLLECT_ECHO", "ECHO_SUMMARY", "CHECK_DESC", "HW_TYPE", "ASSET_IP", "AUDIT_STATUS", "AUDIT_DESC", "COMMIT_STATUS") VALUES ($id, $taskId, 'SEC-CI-CONTAINER-71', $assetId, '1', '2024-07-29 16:54:54 任务结束，耗时4分10秒
# 2024-07-29 16:54:54 基线配置扫描结束
# 2024-07-29 16:50:43 任务开始执行', $saveTime, '@@@@@@@@@@【CKPT4073078710583531】检查是否对docker.socket文件开启审计策略``````````auditctl -l |grep docker.socket;auditctl -l |grep /etc/default/docker````````````````````0``````````2``````````1``````````>=', '2024-07-29 16:54:53 检查点【CKPT4073078710583531】采集结果不满足判定标准【>=2】
# ', NULL, 'DR-LIN', $iIP, NULL, NULL, NULL);
#     """, seep)


# file.writelines(list[0])
# file.writelines(list[1])
# file.writelines(list[2])
# file.writelines(list[3])
